package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.common.params.PageQueryParam;
import com.itheima.common.vo.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

//No provider available
@RestController
@RequestMapping("checkItem")
public class CheckItemController {

    @Reference(version = "1.0")
    private CheckItemService checkItemService;

    // /checkItem/findPage.do
    @PostMapping("findPage")
//    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")
    public Result findPage(@RequestBody PageQueryParam pageQueryParam){
        return checkItemService.findPage(pageQueryParam);
    }
    @PostMapping("add")
//    @PreAuthorize("hasAuthority('CHECKITEM_ADD')")
    public Result add(@RequestBody CheckItem checkItem){
        return checkItemService.save(checkItem);
    }
    @PostMapping("update")
//    @PreAuthorize("hasAuthority('CHECKITEM_EDIT')")
    public Result update(@RequestBody CheckItem checkItem){
        return checkItemService.update(checkItem);
    }

    @GetMapping("findById/{id}")
//    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")
    public Result findById(@PathVariable("id") Integer id){
        return checkItemService.findById(id);
    }
    @GetMapping("delete/{id}")
//    @PreAuthorize("hasAuthority('CHECKITEM_DELETE')")
    public Result delete(@PathVariable("id") Integer id){
        return checkItemService.delete(id);
    }

    @Autowired
    private JedisPool jedisPool;

    @GetMapping("findAll")
    public Result findAll(){
        //需要做优化，加缓存
        //如果缓存中有，从缓存中取 ，如果没有 调用dubbo服务，获取结果，存入缓存
        //存缓存的时候 设置过期时间
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //string  key-value   key:checkItem_all value: Result（data=checkItemList）json
            String checkItemAll = jedis.get("checkItem_all");
            if (StringUtils.isNotBlank(checkItemAll)){
                return JSON.parseObject(checkItemAll,Result.class);
            }
            Result all = checkItemService.findAll();
            jedis.setex("checkItem_all",5*60,JSON.toJSONString(all));
            return all;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return Result.fail();
    }
}
